﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HTTPServerLib;

namespace HttpTest
{
    public class HttpServer : HTTPServerLib.HttpServer
    {
        public delegate string RequestDelegate(string endpoint,string requestBody,HttpClient.RequestMethod requestMethod);
        public event RequestDelegate onRequest;


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ipAddress">IP地址</param>
        /// <param name="port">端口号</param>
        public HttpServer(string ipAddress, int port)
            : base(ipAddress, port)
        {

        }
        void send_response(HTTPServerLib.HttpResponse response,string responseBody)
        {
            //构造响应报文
            response.SetContent(responseBody);
            response.Content_Encoding = "utf-8";
            response.StatusCode = "200";
            response.Content_Type = "application/json";
            response.Content_Length = responseBody.Length.ToString();
            response.SetHeader("Server", "PC");

            response.Send();
        }
        public override void OnPost(HTTPServerLib.HttpRequest request, HTTPServerLib.HttpResponse response)
        {
            string content =  onRequest?.Invoke(request.URL, request.Body, HttpClient.RequestMethod.POST);
            if (content!=null)
            {
                send_response(response, content);
            }
            

            ////构造响应报文
            //response.SetContent(content);
            //response.Content_Encoding = "utf-8";
            //response.StatusCode = "200";
            //response.Content_Type = "application/json; charset=UTF-8";
            //response.Send();
        }

        public override void OnGet(HttpRequest request, HttpResponse response)
        {
            string content = onRequest?.Invoke(request.URL, request.Body, HttpClient.RequestMethod.GET);
            if (content != null)
            {
                send_response(response, content);
            }
        }

        public override void OnDefault(HttpRequest request, HttpResponse response)
        {
            if (request.Method=="DELETE")
            {
                string content = onRequest?.Invoke(request.URL, request.Body, HttpClient.RequestMethod.DELETE);
                if (content != null)
                {
                    send_response(response, content);
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("UNKNOW  request method");
            }
            
        }

    }
}
